package com.haohan.stock.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.haohan.stock.domain.StockData;
import com.haohan.stock.vo.SpringDataPageable;

@Component
public class OperateDAO {

	@Autowired
	public MongoTemplate mongoTemplate;

	public List<StockData> selectAll(String code,int scale) {
		Criteria criteria = Criteria.where("code").is(code);
		criteria.andOperator(Criteria.where("scale").is(scale));
		Query query = Query.query(criteria);
		List<Order> orders = new ArrayList<Order>(); // 排序
		orders.add(new Order(Direction.DESC, "day"));
		Sort sort = new Sort(orders);
		SpringDataPageable pageable =   new SpringDataPageable();
		pageable.setSort(sort);
		return mongoTemplate.find(query.with(pageable), StockData.class);
	}

	public void saveAsMongo(StockData stock) {
		boolean a = true;
		try {
			while(a){
				Criteria criteria = Criteria.where("day").is(stock.getDay());
				criteria.andOperator(Criteria.where("code").is(stock.getCode()));
				Query query = Query.query(criteria);
				Update update = Update.update("open", stock.getOpen());
				update.set("high", stock.getHigh());
				update.set("low", stock.getLow());
				update.set("close", stock.getClose());
				update.set("volume", stock.getVolume());
				update.set("price5", stock.getPrice5());
				update.set("price10", stock.getPrice10());
				update.set("price20", stock.getPrice20());
				update.set("price30", stock.getPrice30());
				update.set("volume5", stock.getVolume5());
				update.set("volume10", stock.getVolume10());
				update.set("volume20", stock.getVolume20());
				update.set("volume30", stock.getVolume30());
				update.set("upward_momentum", stock.getUpward_momentum());
				update.set("buy_point", stock.isBuy_point());
				update.set("sell_point", stock.isSell_point());
				update.set("scale", stock.getScale());
				mongoTemplate.upsert(query, update, StockData.class);
				a=false;
			}
		} catch (Exception e) {
		}
	}
}
